#pragma once
#define _FIFO_FILE "fifo"
#include <iostream>
#include <sys/types.h>
#include <string>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
using namespace std;

class IpcFifio
{
public:
    IpcFifio( const string path,const string name)
        :  _path(path),_name(name), _fd(-1)
    {
        _fifoname = _path + "/" + _name;
        int n = mkfifo(_fifoname.c_str(), 0666);
        if (n < 0)
        {
            cout << "mkfifo error" << endl;
        }
        else
        {
            cout << "mkfifo success" << endl;
        }
    }
    ~IpcFifio()
    {
        close(_fd);

        // s删除管道
        int n = unlink(_FIFO_FILE);
        if (n == 0)
        {
            cout << "remove fifo success" << endl;
        }
        else
        {
            cout << "remove fifo failed" << endl;
        }
    }

private:
    string _path;
    string _name;
   
    string _fifoname;
    pid_t _fd;
};

class FileOper
{
public:
    FileOper( const string path,const string name)
        :  _path(path),_name(name),_fd(-1)
    {
        _fifoname = _path + "/" + _name;
    }
    void OpenForRead()
    {
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            cout << "open fifo error";
            return;
        }
    }
    void OpenForWrite()
    {
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            cout << "write fifo error";
            return;
        }
        cout<<"file open success"<<endl;
    }
    void Write()
    {
        string message;
        pid_t id=getpid();
        int cnt=1;
        while(true)
        {
            cout<<"please enter# :";
            getline(cin,message);
    
            message+=",message number: "+to_string(cnt++)+",["+to_string(id)+"]";
            int n=write(_fd,message.c_str(),message.size());
            if(n<0)
            {
                cout<<"read error"<<endl;
                break;
            }
            
        }
    }
    void Read()
    {
        char buffer[1024];
    while (true)
    {
        int n = read(_fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "client say#:" << buffer << endl;
        }
        else if (n == 0)
        {
            cout << "客户端退出，服务端正常退出" << endl;
            break;
        }
        else
        {
            cout << "read error" << endl;
            break;
        }
    }
    }
    void Close()
    {
        if(_fd>0)
        {
            close(_fd);
        }
    }
    ~FileOper()
    {
    }

private:
    string _path;
    string _name;
    
    string _fifoname;
    pid_t _fd;
};